//
//  TripViewController.m
//  RoadLine
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 RedFireNoodles. All rights reserved.
//
//KennethWang 途行日记 (自定义cell是TripTblCell)
#import "TripViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "HighQualityTripModel.h"
#import "TripTblCell.h"
#import "TripDetailViewController.h"
#import "TripDetailViewModel.h"
#import "Constants.h"

@interface TripViewController ()

//@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *detailArray;
@property(nonatomic, retain)UIActivityIndicatorView *activity;
@property(nonatomic, assign)BOOL isloaded;
@end

@implementation TripViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.detailArray = [NSMutableArray array];
    }
    return self;
}
// AFN解析过方法;
- (void)loading
{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^{
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
      //  http://api.breadtrip.com/trips/2387691349/waypoints/
        // 属性传值第三步 使用值;
        NSString *Str = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/%@/",self.highQualityTripModelId,self.htmlLatsStr];
        [manager GET:Str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 解析过程
            // 最外层字典;
            NSMutableDictionary *dic = responseObject;
            // 内层数组
            if ([self.htmlLatsStr isEqualToString:@"trackpoints"]) {
                NSArray *array = [dic objectForKey:@"trackpoints"];
                for (NSArray *arr in array) {
                    if (![arr[6] isEqualToString:@""] || ![arr[5] isEqualToString:@""]) {
                        [self.detailArray addObject:arr];
                    }
                }
            }else if([self.htmlLatsStr isEqualToString:@"waypoints"]){
                NSMutableArray *arr = [NSMutableArray array];
                arr = [dic objectForKey:@"days"];
                NSMutableArray *wayPointArr = [NSMutableArray array];
                for (NSMutableDictionary *dic in arr) {
                    [wayPointArr addObject:[dic objectForKey:@"waypoints"]];
                }
                for (NSInteger i = 0; i < wayPointArr.count; i++) {
                    for (NSMutableDictionary *dic in wayPointArr[i]) {
                        TripDetailViewModel *trip = [[TripDetailViewModel alloc] init];
                        [trip setValuesForKeysWithDictionary:dic];
                        [self.detailArray addObject:trip];
                        [trip release];
                    }
                }
            }
            [self.tableView reloadData];
            [self.activity stopAnimating];
            self.isloaded = YES;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self.activity stopAnimating];
        }];

    });
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.isloaded = NO;
    // 改变uinavigationBar 的title颜色
    UILabel *titleLabelPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabelPrice.font = [UIFont boldSystemFontOfSize:18];
    titleLabelPrice.textColor = [UIColor whiteColor];
    titleLabelPrice.backgroundColor = [UIColor clearColor];
    titleLabelPrice.text = @"    途行日记";
    self.navigationItem.titleView = [titleLabelPrice autorelease];
    
    // 创建tableView;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    self.tableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.activity];
    self.activity.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
    [self.activity startAnimating];
    [_activity release];
    [_tableView release];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 调用解析方法;
    [self loading];
    
    
}
// 实现cell的高度方法;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  240;
}

// tableView必须实现的两个方法;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = self.detailArray.count;
    if (count == 0 && self.isloaded) {
        UILabel *lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 200, 60)];
        lblMsg.text = @"亲,该日记不存在!";
        [self.view addSubview:lblMsg];
        [lblMsg release];
    }
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 重用池;
    static NSString *reuseTripView = @"reuseTripView";
    TripTblCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseTripView];
    if (cell == nil) {
        cell = [[[TripTblCell alloc]initWithStyle:0 reuseIdentifier:reuseTripView]autorelease];
    }
    if ([Singleton shareSingleton].isNight) {
        [[Singleton shareSingleton] loadNightModeInfoFormDisk];
    }
    cell.tripTblLabel.text = self.detailArray[indexPath.row][5];
    if ([cell.tripTblLabel.text isEqualToString:@""]) {
        cell.tripTblLabel.text = @"这里只欣赏图片就好";
    }
    // 占位图代码;
    NSURL *url = [NSURL URLWithString:self.detailArray[indexPath.row][6]];
    [cell.tripTblImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"BEIJING.png"]];
    cell.contentView.backgroundColor = [UIColor colorWithRed:250/255.0 green:245/255.0 blue:232/255.0 alpha:1];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
    // cell的点击方法:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TripDetailViewController *tripDetailVC = [[TripDetailViewController alloc]init];
    [self.navigationController pushViewController:tripDetailVC animated:YES];
    // 赋值;
    tripDetailVC.tripDetailViewText= self.detailArray[indexPath.row][5];
    tripDetailVC.tripDetailViewUrl = self.detailArray[indexPath.row][6];
    [tripDetailVC release];
}
- (void)setLightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:246/255.0 green:85/255.0 blue:91/255.0 alpha:1];
}

- (void)setNightDayModel {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:4/255.0 green:165/255.0 blue:171/255.0 alpha:1];
}
    // 内存管理;
- (void)dealloc
{
    [_activity release];
    [_tableView release];
    [_detailArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
